from django.shortcuts import render
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.response import Response
from rest_framework import status
from .serializers import MovieOrdersSerializer, MovieOrdersCreateSerializer
from utils.my_ali import get_order_url
from rest_framework.views import APIView
from .models import MovieOrders
from urllib.parse import urldefrag,unquote
from django.http import HttpResponse, JsonResponse


# Create your views here.

class MovieOrderViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
                        mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
    list:
        用户查看自己的所有订单
    retrieve:
        用户查看自己的单条订单
    create:
        用户创建一条订单(够买电影票)
    destroy:
        用户删除一条订单
    """

    serializer_class = MovieOrdersSerializer
    queryset = serializer_class.Meta.model.objects.all()
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    permission_classes = (permissions.IsAuthenticated,)

    def get_serializer_class(self):
        if self.action == "create":
            return MovieOrdersCreateSerializer

        return self.serializer_class

    def get_queryset(self):
        user = self.request.user
        return self.serializer_class.Meta.model.objects.filter(user=user)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        from movies.serializers import FilmScheduleSerializer
        data = serializer.data
        ins = serializer.instance
        order_num = ins.order_num.hex
        url = get_order_url(order_num, ins.price, debug=True)

        #url = "https://openapi.alipaydev.com/gateway.do?app_id=2016091800541924&biz_content=%7B%22subject%22%3A%22p1802%22%2C%22out_trade_no%22%3A%227e0e937cd2a041f9ac8df21db276c6cf%22%2C%22total_amount%22%3A1000.0%2C%22product_code%22%3A%22FAST_INSTANT_TRADE_PAY%22%7D&charset=utf-8&method=alipay.trade.page.pay&notify_url=https%3A%2F%2Fexample.com%2Fnotify&return_url=http%3A%2F%2F127.0.0.1%3A8004%2Forders%2Fali%2Fnotify&sign_type=RSA2&timestamp=2018-08-09+01%3A11%3A42&version=1.0&sign=mH67vJ%2FpUNzYvDNUthIb8Pg%2ByDXMDyp1HGdpRswHYEG89yGjY92SptTzsrTShRkOyfn0EB69Vu3rKAvz8YMOxS%2FfqwqXCs8GWyAzrMhWpv01iNW4qQovcS%2BnvOAv6hXBFZ4G622DliWZ7WLAFhuUfZxG4tF5kbkTH1VTXS25kplHpAZLABWonU52LZxoon%2BizF4%2BWEZTipsNyBr63Xk%2B0l5jGmsVohc%2F9J7i0D%2BRRS%2BlkL%2FPjEH2CeM6sToSJwyq%2BsDYKcxJ95C6eOOUh0K%2BGzOjrymlYKSx04cHQRkhxIR6UCJ1IKaHSgy1%2B97hCpjLTac9vyHbpCVgEKhjNCWCHQ%3D%3D"
        data.update({
            'pay_url': url,
        })

        """
        1.座位的详细 行列
        2.片场
            1. 影厅信息-+
        """

        test = FilmScheduleSerializer(ins.film_schedule)
        data.update(test.data)

        #return Response(url)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)



"""
接收支付成功之后的回调
"""
from alipay import AliPay

import os
from django3 import settings


class AliPayNotify(APIView):

    def __init__(self):

        private_key_path = os.path.join(settings.BASE_DIR, 'keys', 'rsa_private_key.pem')
        public_key_path = os.path.join(settings.BASE_DIR, 'keys', 'ali_pub')
        app_private_key_string = open(private_key_path).read()
        alipay_public_key_string = open(public_key_path).read()
        appid = "2016091800541924"

        self.alipay = AliPay(
            appid=appid,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False  # 默认False
        )

        super().__init__()


    def post(self,request):

        tmp = request.query_params.dict()

        signature = tmp.pop("sign")

        # print(json.dumps(data))
        # print(signature)

        # verify
        success = self.alipay.verify(tmp, signature)
        if not success:
            return Response('false', status=status.HTTP_400_BAD_REQUEST)

        order_num = tmp['out_trade_no']
        amount = float(tmp['total_amount'])
        order_manger = MovieOrders.objects.filter(order_num=order_num)
        if not order_manger.exists():
            return Response('no order')
        order = order_manger[0]

        if amount != order.price:
            return Response('order price invalid')

        order.pay_num = tmp['trade_no']
        order.status = '2'
        # 遍历所有的座位信息
        for i in order.seats.all():
            i.status = '2'
            i.owner = order.user
            i.save()

        order.save()
        return Response('success')



    def get(self, request):



        tmp = request.query_params.dict()

        signature = tmp.pop("sign")

        # print(json.dumps(data))
        # print(signature)

        # verify
        success = self.alipay.verify(tmp, signature)
        if not success:

            return Response('false',status=status.HTTP_400_BAD_REQUEST)

        order_num = tmp['out_trade_no']
        amount = float(tmp['total_amount'])
        print(order_num)
        order_manger = MovieOrders.objects.filter(order_num=order_num)
        if not order_manger.exists():
            return Response('no order')
        order = order_manger[0]

        if amount != order.price:
            return Response('order price invalid')

        order.pay_num = tmp['trade_no']
        order.status = '2'
        # 遍历所有的座位信息
        for i in order.seats.all():
            i.status = '2'
            i.owner = order.user
            i.save()

        order.save()
        return Response('success')
